package com.miya.order.configure.rabbitmq.topic;

import com.alibaba.fastjson.JSONObject;
import com.miya.constant.MiyaConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 主题演示配置
 *
 * @author Caixiaowei
 * @date 2022/01/20
 */
@Configuration
@Slf4j
public class TopicDemoConfigure {

    @Bean
    public Queue topicDemoQueue() {
        return new Queue(MiyaConstant.TOPIC_DEMO_QUEUE);
    }

    @Bean
    public TopicExchange topicDemoExchange() {
        return new TopicExchange(MiyaConstant.TOPIC_DEMO_EXCHANGE);
    }

    @Bean
    public Binding bindingApproval() {
        //绑定一个队列 to: 绑定到哪个交换机上面 with：绑定的路由建（routingKey）
        return BindingBuilder.bind(topicDemoQueue()).to(topicDemoExchange()).with(MiyaConstant.TOPIC_DEMO_ROUTKEY);
    }

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack) {
                    // 发送成功
                    log.info("rabbit 发送成功 data: {}, ack:{}, cause: {}", JSONObject.toJSONString(correlationData), ack, cause);
                } else {
                    // 发送失败
                    log.info("rabbit 发送失败 data: {}, ack:{}, cause: {}", JSONObject.toJSONString(correlationData), ack, cause);
                }
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                // 发送回调失败
                log.error("rabbit 回调失败 消息 message:{}, 回应码 replyCode: {}, 回应信息 replyText: {}, 交换机 exchange: {}, 路由键 routingKey: {}",
                        message, replyCode, replyText, exchange, routingKey);
            }
        });

        return rabbitTemplate;
    }
}
